package com.ruoyi.rural.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.rural.domain.RiskArea;
import com.ruoyi.rural.domain.RuralUser;
import com.ruoyi.rural.service.IRuralUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息Controller
 * 
 * @author 杨明
 * @date 2022-01-17
 */
@RestController
@RequestMapping("/ruralUser")
public class RuralUserController extends BaseController
{
    @Autowired
    private IRuralUserService ruralUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询用户信息列表
     */
    @RequiresPermissions("rural:ruralUser:list")
    @GetMapping("/list")
    public TableDataInfo list(RuralUser ruralUser)
    {
        startPage();
        List<RuralUser> list = ruralUserService.selectRuralUserList(ruralUser);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @RequiresPermissions("rural:ruralUser:export")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RuralUser ruralUser)
    {
        List<RuralUser> list = ruralUserService.selectRuralUserList(ruralUser);
        ExcelUtil<RuralUser> util = new ExcelUtil<RuralUser>(RuralUser.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @RequiresPermissions("rural:ruralUser:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(ruralUserService.selectRuralUserById(id));
    }

    /**
     * 新增用户信息
     */
    @RequiresPermissions("rural:ruralUser:add")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RuralUser ruralUser)
    {
        return toAjax(ruralUserService.insertRuralUser(ruralUser));
    }

    /**
     * 修改用户信息
     */
    @RequiresPermissions("rural:ruralUser:edit")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RuralUser ruralUser)
    {
        return toAjax(ruralUserService.updateRuralUser(ruralUser));
    }

    /**
     * 删除用户信息
     */
    @RequiresPermissions("rural:ruralUser:remove")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(ruralUserService.deleteRuralUserByIds(ids));
    }


    /**
     * 中高风险用户
     */
    @RequiresPermissions("rural:ruralUser:list")
    @GetMapping("/riskUserList")
    public AjaxResult riskUserList(RiskArea riskArea)
    {
        System.out.println(riskArea);
        String riskAreaData = "";
        RuralUser ruralUser = new RuralUser();
        if (redisTemplate.hasKey("riskAreaData")){
            riskAreaData = (String) redisTemplate.opsForValue().get("riskAreaData");
        }else {
            riskAreaData = getRiskAreaData();
            if (StringUtils.isEmpty(riskAreaData)){
                return AjaxResult.error("接口请求数据错误！");
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(riskAreaData);
        String data = jsonObject.getString("data");
        List<RiskArea> riskAreas = JSONObject.parseArray(data, RiskArea.class);
        List<RuralUser> list = ruralUserService.selectRuralUserList(ruralUser);
        List<RuralUser> riskUserList = new ArrayList<>();
        for (RuralUser user : list) {
            String currentCity = user.getCurrentCity().replaceAll(",","");
            for (RiskArea riskArea1 : riskAreas) {
                if ((StringUtils.isNotEmpty(riskArea.getType()) && riskArea1.getType().equals(riskArea.getType()))||StringUtils.isEmpty(riskArea.getType())){
                    if (riskArea1.getArea().indexOf(currentCity) != -1){
                        user.setRiskLevel(riskArea1.getType());
                        riskUserList.add(user);
                        break;
                    }
                }
            }
        }
        return AjaxResult.success(riskUserList);
    }

    public String getRiskAreaData(){
        String path = "https://eyesight.news.qq.com/sars/riskarea";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("GET");//GET和POST必须全大写
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            String response = "";
            while ((str = br.readLine()) != null) {
                str=new String(str.getBytes(),"UTF-8");//解决中文乱码问题
                redisTemplate.opsForValue().set("riskAreaData", str, 1, TimeUnit.DAYS);
                return str;
            }
            is.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }
}
